#!/usr/bin/env python
import os
import sys
import string
import time
import datetime
import MySQLdb
import pymssql
import redis
import logging
import logging.config
logging.config.fileConfig("etc/logger.ini")
logger = logging.getLogger("lepus")
path='./include'
sys.path.insert(0,path)
import functions as func
from multiprocessing import Process;

def check_sqlserver(host,port,username,password,server_id,tags):
    try:
        conn = pymssql.connect(host=host,port=int(port),user=username,password=password,charset="utf8")
        cur = conn.cursor()
        #version
        version_row = cur.execute("SELECT @@VERSION AS [SQL Server and OS Version Info];")
        version_item = cur.fetchone()
        version =  version_item[0]
        #os_sys_info
        os_sys_info_row =  cur.execute("SELECT cpu_count AS [Logical CPU Count],cpu_count/hyperthread_ratio AS [Physical CPU Count],physical_memory_kb/1024 AS [Physical Memory (MB)], sqlserver_start_time FROM master.sys.dm_os_sys_info WITH (NOLOCK) OPTION (RECOMPILE);") 
        os_sys_info_item = cur.fetchone()
        logical_cpu_count = os_sys_info_item[0]
        physical_cpu_count = os_sys_info_item[1]
        physical_memory = os_sys_info_item[2]
        start_time = os_sys_info_item[3]
        

        conn.close()
   
    except Exception, e:
        logger_msg="check redis %s:%s : %s" %(host,port,e)
        logger.warning(logger_msg)
    finally:
        sys.exit(1)

def main():

    servers = func.mysql_query('select id,host,port,username,password,tags from db_servers_sqlserver where is_delete=0 and monitor=1;')

    logger.info("check sqlserver controller started.")

    if servers:
         plist = []

         for row in servers:
             server_id=row[0]
             host=row[1]
             port=row[2]
             username=row[3]
             password=row[4]
             tags=row[4]
             p = Process(target = check_sqlserver, args = (host,port,username,password,server_id,tags))
             plist.append(p)
             p.start()

         for p in plist:
             p.join()

    else:
         logger.warning("check sqlserver: not found any servers")

    logger.info("check sqlserver controller finished.")

if __name__=='__main__':
    main()
